package org.byqh.dqeai.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.byqh.dqeai.common.Json;
import org.byqh.dqeai.dto.EaiSysRoleDTO;
import org.byqh.dqeai.entity.EaiSysRole;
import org.byqh.dqeai.entity.EaiSysRoleModule;
import org.byqh.dqeai.entity.EaiSysUserRole;
import org.byqh.dqeai.entity.proxy.EaiSysRoleProxy;
import org.byqh.dqeai.enums.SystemEnum;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/sysrole")
@Tag(name = "系统[EaiSysRole] - 角色管理")
public class EaiSysRoleController extends BaseController<EaiSysRole, EaiSysRoleProxy> {
    @Override
    @GetMapping(value = "/get/{id}")
    public Json<EaiSysRole> get(String id) {
        return super.get(id);
    }

    @Override
    @PutMapping(value = "/put")
    public Json<Boolean> put(EaiSysRole dto) {
        return super.put(dto);
    }

    @Override
    @PostMapping(value = "/post")
    public Json<Boolean> post(EaiSysRole dto) {
        return super.post(dto);
    }

    /**
     * 获取某一个具体对象信息
     */
    @GetMapping(value = "/{id}")
    public Json<EaiSysRoleDTO> get2(@PathVariable String id) {
        var obj = getEntityQueryable()
                .whereById(id)
                .selectAutoInclude(EaiSysRoleDTO.class)
                .firstOrNull();

        return Json.success(obj);
    }

    /**
     * 新增某一个具体对象信息
     */
    @PostMapping(value = "/")
    public Json<Boolean> post2(@RequestBody EaiSysRoleDTO dto) {
        var now = LocalDateTime.now();

        dto.setUpdateDate(now);
        dto.setCreateDate(now);

        return easyEntityQuery.insertable(dto).executeRows() > 0 ? Json.success() : Json.error();
    }

    /**
     * 删除某一个具体对象信息
     */
    @DeleteMapping(value = "/{id}")
    public Json<Boolean> delete(@PathVariable String id) {
        if (StringUtils.isBlank(id)) {
            return Json.error(SystemEnum.USER_OPREATION_ENUM.OPERATION_FAIL.getValue(), false, HttpStatus.OK.value());
        }

        // 1.删除角色用户关联表信息
        easyEntityQuery.deletable(EaiSysUserRole.class)
                .disableLogicDelete()
                .allowDeleteStatement(true)
                .where(e -> e.roleId().eq(id)).executeRows();

        // 2.删除角色业务关联表信息
        easyEntityQuery.deletable(EaiSysRoleModule.class)
                .disableLogicDelete()
                .allowDeleteStatement(true)
                .where(e -> e.roleId().eq(id)).executeRows();

        // 3.删除角色信息
        this.removeById(id);

        return Json.success();
    }

    /**
     * 修改某一个具体对象信息
     */
    @PutMapping(value = "/")
    public Json<Boolean> put2(@RequestBody EaiSysRoleDTO dto) {
        dto.setUpdateDate(LocalDateTime.now());
        return easyEntityQuery.updatable(dto).executeRows() > 0 ? Json.success() : Json.error();
    }

    /**
     * 根据角色分类ID，CATEGORY_ID获取分类 (包括子分类 下所有的角色列表，当CATEGORY_ID为空时查询所有，按角色创建时间排序)
     */
    @GetMapping(value = "/listByRoleIdAndCId")
    public Json<List<EaiSysRoleDTO>> listByRoleIdAndCId(
            @RequestParam(defaultValue = "", required = false) String roleId,
            @RequestParam(defaultValue = "", required = false) String categoryId) {

        return this.listImpl(EaiSysRoleDTO.class, query -> {
            if (StringUtils.isBlank(categoryId)) {
                return query.where(o -> o.roleId().eq(roleId))
                        .orderBy(e -> e.createDate().desc());
            } else {
                String sql = String.format("""
                        select CATEGORY_ID
                                FROM EAI_SYS_BUSINESS_CATEGORY
                                start with CATEGORY_ID = '%s'
                                connect by prior CATEGORY_ID = PARENT_CATEGORY_ID
                        """, categoryId);

                return query.where(o -> o.categoryId().in(easyQueryClient.queryable(sql, String.class)))
                        .orderBy(e -> e.createDate().desc());
            }
        });
    }

    /**
     * 根据用户ID，能够获取用户分配的所有角色列表
     */
    @GetMapping(value = "/listByUserId")
    public Json<List<EaiSysRoleDTO>> listByUserId(
            @RequestParam(defaultValue = "", required = false) String sysUserId) {
        if (StringUtils.isBlank(sysUserId)) {
            return Json.errorT("参数为空");
        }

        String sql = String.format("""
                select ROLE_ID
                    FROM EAI_SYS_USER_ROLE
                    where USER_ID = '%s'
                """, sysUserId);

        return this.listImpl(EaiSysRoleDTO.class, query ->
                query.where(e -> e.roleId().in(easyQueryClient.queryable(sql, String.class))));
    }

    /**
     * 根据业务ID，能够获取业务功能所分配的角色列表
     */
    @GetMapping(value = "/listByBusinessId")
    public Json<List<EaiSysRoleDTO>> listByBusinessId(
            @RequestParam(defaultValue = "", required = false) String businessId
    ) {
        if (StringUtils.isBlank(businessId)) {
            return Json.errorT("参数为空");
        }

        String sql = String.format("""
                select ROLE_ID
                     FROM EAI_SYS_ROLE
                     where BUSINESS_ID = '%s'
                """, businessId);

        return this.listImpl(EaiSysRoleDTO.class, query ->
                query.where(e -> e.roleId().in(easyQueryClient.queryable(sql, String.class))));
    }

    /**
     * 根据业务ID，能够获取业务功能所分配的角色列表
     */
    @GetMapping(value = "/listByModuleId")
    public Json<List<EaiSysRoleDTO>> listByModuleId(
            @RequestParam(defaultValue = "", required = false) String moduleId
    ) {
        if (StringUtils.isBlank(moduleId)) {
            return Json.errorT("参数为空");
        }

        String sql = String.format("""
                select ROLE_ID 
                    FROM Eai_Sys_Role_Module 
                    where module_id = '%s'
                """, moduleId);

        return this.listImpl(EaiSysRoleDTO.class, query ->
                query.where(e -> e.roleId().in(easyQueryClient.queryable(sql, String.class))));
    }

    /**
     * 查询对象信息列表
     */
    @PostMapping(value = "/list")
    public Json<List<EaiSysRoleDTO>> list(@RequestBody(required = false) EaiSysRoleDTO dto) {
        return this.listImpl(EaiSysRoleDTO.class, query -> {
            String roleName = dto.getRoleName() == null ? ""
                    : dto.getRoleName().trim();

            String categoryId =
                    dto.getCategoryId() == null ? ""
                            : dto.getCategoryId().trim();
            String appId =
                    dto.getAppId() == null ? ""
                            : dto.getAppId().trim();

            String userId =
                    dto.getUserId() == null ? ""
                            : dto.getUserId().trim();

            if (!StringUtils.isBlank(appId)) {
                query = query.where(e -> e.appId().eq(appId));
            }

            if (!StringUtils.isBlank(categoryId)) {
                query = query.where(e -> e.categoryId().eq(categoryId));
            }

            if (!StringUtils.isBlank(roleName)) {
                query = query.where(e -> e.roleName().eq(roleName));
            }

            if (!StringUtils.isBlank(userId)) {
                var subquery = easyEntityQuery.queryable(EaiSysUserRole.class)
                        .where(e -> e.userId().eq(userId))
                        .select(e -> e.roleId());

                query = query.where(e -> e.roleId().in(subquery));
            }

            if (dto.getRoleidList() != null) {
                query = query.where(e -> e.roleId().in(dto.getRoleidList()));
            }

            return query;
        });
    }
}